const express = require('express');
const cors = require('cors');
const path = require('path');
require('dotenv').config();

const app = express();

// 静态文件服务
app.use(
  '/uploads',
  express.static(path.join(__dirname, '../public/uploads'), {
    setHeaders: (res, path, stat) => {
      res.set('Access-Control-Allow-Origin', '*');
      res.set('Access-Control-Allow-Methods', 'GET');
      res.set('Cache-Control', 'public, max-age=31536000'); // 缓存一年
    },
  })
);

// CORS配置
app.use(
  cors({
    origin: ['http://localhost:5174', 'http://127.0.0.1:5174'],
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: [
      'Content-Type',
      'Authorization',
      'X-Requested-With',
      'Accept',
      'Origin',
      'x-access-token',
    ],
    exposedHeaders: ['Authorization'],
    maxAge: 86400, // 预检请求缓存24小时
  })
);

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} ${req.method} ${req.url}`);
  next();
});

// 路由
try {
  app.use('/api/users', require('./routes/users.routes.js'));
  app.use('/api/courses', require('./routes/courses.routes.js'));
  app.use('/api/consultations', require('./routes/consultations.routes.js'));
  app.use('/api/events', require('./routes/events.routes.js'));
  app.use('/api/knowledge', require('./routes/knowledge.routes.js'));
} catch (error) {
  console.error('Route loading error:', error);
}

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('Error details:', {
    message: err.message,
    stack: err.stack,
    url: req.url,
    method: req.method,
    body: req.body,
  });
  res.status(500).json({
    message: '服务器错误',
    details: process.env.NODE_ENV === 'development' ? err.message : undefined,
  });
});

// 404处理
app.use((req, res) => {
  res.status(404).json({ message: '接口不存在' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
  console.log('Environment:', {
    NODE_ENV: process.env.NODE_ENV,
    PORT: process.env.PORT,
    DB_HOST: process.env.DB_HOST,
    DB_NAME: process.env.DB_NAME,
    FRONTEND_URL: process.env.FRONTEND_URL,
  });
});
